const app = getApp()

Page({
  data: {
    phone: '',
    password: '',
    loading: false
  },

  onLoad() {
    // 检查是否已登录
    if (app.checkTechnicianLogin()) {
      wx.redirectTo({
        url: '/pages/worker/index'
      });
    }
  },

  // 输入手机号
  inputPhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  // 输入密码
  inputPassword(e) {
    this.setData({
      password: e.detail.value
    })
  },

  // 登录
  async login() {
    console.log('login方法被调用')
    if (!this.data.phone || !this.data.password) {
      wx.showToast({
        title: '请输入手机号和密码',
        icon: 'none'
      })
      console.log('未输入手机号或密码')
      return
    }

    this.setData({ loading: true })

    try {
      const res = await app.request({
        url: '/api/technicians/login',
        method: 'POST',
        data: {
          phone: this.data.phone,
          password: this.data.password
        }
      })

      if (res.statusCode === 200 && res.data) {
        // 打印后端返回的technician对象
        console.log('登录返回的technician:', res.data.technician)
        // 保存token和用户信息
        wx.setStorageSync('technicianToken', res.data.token)
        wx.setStorageSync('technicianInfo', res.data.technician)
        app.globalData.technicianInfo = res.data.technician
        // 打印本地存储后的technicianInfo
        console.log('本地存储的technicianInfo:', wx.getStorageSync('technicianInfo'))
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        })
        // 跳转到工程师主页
        wx.redirectTo({
          url: '/pages/worker/index'
        })
      } else {
        wx.showToast({
          title: res.data || '登录失败',
          icon: 'none'
        })
        console.log('登录失败，后端返回：', res)
      }
    } catch (error) {
      console.error('登录失败：', error)
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      })
      console.log('登录异常', error)
    } finally {
      this.setData({ loading: false })
    }
  }
}) 